package main

import (
	"encoding/binary"
	"fmt"

	"google.golang.org/protobuf/proto"
)

func main() {
	/* 构造config对象数据 */
	var config = PB_TerninalConfigration{
		DeviceInfo: &PB_DeviceInfo{
			TerminalSn: "123456789",
			LogLevel:   1,
		},
		ServerInfo: &PB_ServerInfo{
			Hostname: "baidu.com",
			Port:     8080,
		},
		NetInfo: &PB_NetInfo{
			UseDhcp:    true,
			MacAddr:    []byte{0x12, 0x23, 0x34, 0x56, 0x78, 0x89},
			Ip:         binary.BigEndian.Uint32([]byte{192, 168, 1, 1}),
			SubnetMask: binary.BigEndian.Uint32([]byte{255, 255, 255, 0}),
			Gateway:    binary.BigEndian.Uint32([]byte{192, 168, 1, 1}),
			Dns:        binary.BigEndian.Uint32([]byte{192, 168, 1, 1}),
		},
	}

	/* 原始数据 */
	fmt.Println("原始数据：")
	fmt.Println(config.String())

	/* 序列化 */
	fmt.Println("序列化后的数据：")
	var marshal_bytes, _ = proto.Marshal(&config)
	fmt.Println(format_bytes(marshal_bytes))

	/* 反序列化 */
	fmt.Println("反序列化后的数据：")
	var unmarshal_config PB_TerninalConfigration
	proto.Unmarshal(marshal_bytes, &unmarshal_config)
	fmt.Println(unmarshal_config.String())
}

func format_bytes(data []byte) string {
	var formattedBytes string
	for _, b := range data {
		formattedBytes += fmt.Sprintf("%02x ", b)
	}
	return formattedBytes[:len(formattedBytes)-1] // 去除最后一个空格
}
